// Kony

#include "Component/TargetLockComponent.h"
#include "NiagaraSystem.h"
#include "NiagaraComponent.h"
#include "NiagaraFunctionLibrary.h"
#include "Interaction/CombatInterface.h"

UTargetLockComponent::UTargetLockComponent()
{
	PrimaryComponentTick.bCanEverTick = false;
	EffectComponent = nullptr;
	TargetLockEffect = nullptr;
}

void UTargetLockComponent::BeginPlay()
{
	Super::BeginPlay();
	
	//监听角色死亡广播
	if (ICombatInterface* CombatInterface = Cast<ICombatInterface>(GetOwner()))
	{
		CombatInterface->GetOnDeathDelegate().AddDynamic(this, &UTargetLockComponent::OnOwnerDeath);
	}
}

void UTargetLockComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	HideTargetIndicator();
	Super::EndPlay(EndPlayReason);
}

void UTargetLockComponent::ShowTargetIndicator()
{
	if (!GetOwner() || bIsTargetLocked || !TargetLockEffect) return;

	//创建特效组件并附加到Owner
	EffectComponent = NewObject<UNiagaraComponent>(GetOwner());
	EffectComponent->SetAsset(TargetLockEffect);
	EffectComponent->AttachToComponent(GetOwner()->GetRootComponent(), 
		FAttachmentTransformRules::KeepRelativeTransform);
	EffectComponent->SetRelativeLocation(EffectOffset);
	EffectComponent->RegisterComponent();
	EffectComponent->Activate();
	
	bIsTargetLocked = true;
	
	//广播锁定状态变化
	OnTargetLockChanged.Broadcast(GetOwner(), true);
}

void UTargetLockComponent::HideTargetIndicator()
{
	if (!bIsTargetLocked) return;
	
	bIsTargetLocked = false;
	
	//销毁特效组件
	if (EffectComponent)
	{
		EffectComponent->DestroyComponent();
		EffectComponent = nullptr;
	}
	
	//广播锁定状态变化
	OnTargetLockChanged.Broadcast(GetOwner(), false);
}

void UTargetLockComponent::OnOwnerDeath(AActor* DeadActor)
{
	HideTargetIndicator();
}